﻿using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
 
using System.Linq;
using Mrc.Common.Enum;
using Mrc.Common;

namespace Mrc.Domain.Module.Auth
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class UserLoginAttribute : Attribute, IAuthorizationFilter
    {
        public UserLoginAttribute(){}
        public virtual void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            if (filterContext.Result != null) return;
            //获取token
            var token = "";
            filterContext.HttpContext.Request.Cookies.TryGetValue("MRCTOKEN", out token);
            if (token.IsNullOrEmpty())
            {
                token = filterContext.HttpContext.Request.Headers["MRCTOKEN"].FirstOrDefault();
                if(token == null)
                {
                    Valid(filterContext);
                    return;
                }
            }
            //验证token
            var validateResult = TokenManager.Validate(token, payLoad =>
            {
                var success = true;
                return success && payLoad["aud"]?.ToString() == "user";
            });
            if (validateResult)
            {
                return;
            }
            Valid(filterContext);
            return;
        }
        private void Valid(AuthorizationFilterContext filterContext)
        {
            HttpRequest httpRequest = filterContext.HttpContext.Request;
            if(httpRequest.IsAjaxRequest())
            {
                AjaxResult result = AjaxResult.CreateResult(ResultStatus.NotLogin, "未登录或登录超时，请重新登录");
                string json = JsonHelper.Serialize(result);
                var jsonResult = new JsonResult(result.msg);
                jsonResult.ContentType = "text/json";
                jsonResult.Value = new AjaxResult(ResultStatus.Failed, result.msg);
                filterContext.Result = jsonResult;
                return;
            }
            else
            {
                string url = filterContext.HttpContext.Content("/login");
                url = string.Concat(url, "?returnUrl=", httpRequest.Path);
                RedirectResult redirectResult = new RedirectResult(url);
                filterContext.Result = redirectResult;
                return;
            }
        }
    }
}